"use strict";
const program = require("commander");
const colors = require("colors");
const maxCpus = require("os").cpus().length;
const packageJson = require("../../package.json");

program.on("--help", () => {
  console.log("");
  console.log("  Examples:".blue);
  console.log("");
  console.log("    $ xmysql -u username -p password -h localhost".blue);
  console.log("    $ xmysql --dialect mysql --mysqlConnectionLimit 50 --mysqlDatabase mydb".blue);
  console.log("    $ xmysql --dialect dameng -h localhost -o 5236 -u SYSDBA -p SYSDBA --dmPoolMax 20 --dmPoolMin 5".blue);
  console.log("    $ xmysql --dialect mysql -u root -p password --disableAccessLog".blue);
  console.log("");
});

program
  .version(packageJson.version)
  .option("-h, --host <n>", "hostname of database / localhost by default")
  .option("-u, --user <n>", "username of database / root by default")
  .option("-p, --password <n>", "password of database / empty by default")
  .option("-r, --ipAddress <n>", "IP interface of your server / localhost by default")
  .option("-n, --portNumber <n>", "port number for app / 3000 by default")
  .option("-o, --port <n>", "port number for mysql / 3306 by default")
  .option("-S, --socketPath <n>", "unix socket path / not used by default")
  .option("-s, --storageFolder <n>", "storage folder / current working dir by default / available only with local")
  .option("-i, --ignoreTables <n>", "comma separated table names to ignore")
  .option("-a, --apiPrefix <n>", 'api url prefix / "/api/" by default')
  .option("-y, --readOnly", "readonly apis / false by default")
  .option("-c, --useCpuCores <n>", "use number of CPU cores (using cluster) / 1 by default")
  .option("--disableAccessLog", "disable HTTP access logging for production / false by default")
  .option("--dialect <n>", "database dialect(mysql/dameng). mysql by default")
  // 达梦数据库连接池参数
  .option("--dmPoolAlias <n>", "connection pool alias for dameng database")
  .option("--dmPoolMax <n>", "maximum number of connections in pool / 16 by default for dameng")
  .option("--dmPoolMin <n>", "minimum number of connections in pool / 8 by default for dameng")
  .option("--dmPoolTimeout <n>", "connection idle timeout in seconds, 0 means never close / 60 by default for dameng")
  .option("--dmQueueMax <n>", "maximum queue length for connection requests, -1 means unlimited / 500 by default for dameng")
  .option("--dmQueueRequests", "whether to queue requests when pool reaches max connections / true by default for dameng")
  .option("--dmQueueTimeout <n>", "timeout for queued requests in milliseconds, 0 means wait forever / 60000 by default for dameng")
  .option("--dmTestOnBorrow", "whether to validate connection before use / false by default for dameng")
  .option("--dmValidationQuery <n>", "SQL query for connection validation / 'select 1;' by default for dameng")
  // MySQL连接和连接池参数
  .option("--mysqlDatabase <n>", "name of the database to use for mysql connection")
  .option("--mysqlCharset <n>", "charset for mysql connection / 'UTF8_GENERAL_CI' by default")
  .option("--mysqlTimezone <n>", "timezone for mysql connection / 'local' by default")
  .option("--mysqlConnectTimeout <n>", "connection timeout in milliseconds / 10000 by default")
  .option("--mysqlStringifyObjects", "stringify objects instead of converting to values / false by default")
  .option("--mysqlSupportBigNumbers", "enable support for big numbers (BIGINT and DECIMAL) / false by default")
  .option("--mysqlBigNumberStrings", "return big numbers as strings / false by default")
  .option("--mysqlDateStrings", "return date types as strings / false by default")
  .option("--mysqlMultipleStatements", "allow multiple mysql statements per query / false by default")
  .option("--mysqlTrace", "generate stack traces on errors / true by default")
  .option("--mysqlEnableKeepAlive", "enable keep-alive on socket / true by default")
  .option("--mysqlKeepAliveInitialDelay <n>", "initial delay for keep-alive in milliseconds / 0 by default")
  // MySQL连接池专用参数
  .option("--mysqlWaitForConnections", "wait for connections when pool limit reached / true by default")
  .option("--mysqlConnectionLimit <n>", "maximum number of connections in pool / 10 by default")
  .option("--mysqlMaxIdle <n>", "maximum number of idle connections / same as connectionLimit by default")
  .option("--mysqlIdleTimeout <n>", "idle connections timeout in milliseconds / 60000 by default")
  .option("--mysqlQueueLimit <n>", "maximum queued connection requests, 0 means no limit / 0 by default")
  .parse(process.argv);

function paintHelp(txt) {
  return colors.magenta(txt); //display the help text in a color
}

exports.handle = (program) => {
  /**************** START : default values ****************/
  program.ipAddress = program.ipAddress || "localhost";
  program.portNumber = program.portNumber || 3000;
  program.port = program.port || 3306;
  program.user = program.user || "root";
  program.password = program.password || "";
  program.host = program.host || "localhost";
  program.socketPath = program.socketPath || "";
  program.storageFolder = program.storageFolder || process.cwd();
  program.apiPrefix = program.apiPrefix || "/api/";
  program.readOnly = program.readOnly || false;
  program.useCpuCores = program.useCpuCores || 1;
  program.dialect = program.dialect || "mysql";
  program.disableAccessLog = program.disableAccessLog !== undefined ? program.disableAccessLog : false;

  // 达梦数据库连接池参数默认值
  program.dmPoolAlias = program.dmPoolAlias || "";
  program.dmPoolMax = program.dmPoolMax ? parseInt(program.dmPoolMax) : 16;
  program.dmPoolMin = program.dmPoolMin ? parseInt(program.dmPoolMin) : 8;
  program.dmPoolTimeout = program.dmPoolTimeout ? parseInt(program.dmPoolTimeout) : 60;
  program.dmQueueMax = program.dmQueueMax ? parseInt(program.dmQueueMax) : 500;
  program.dmQueueRequests = program.dmQueueRequests !== undefined ? program.dmQueueRequests : true;
  program.dmQueueTimeout = program.dmQueueTimeout ? parseInt(program.dmQueueTimeout) : 60000;
  program.dmTestOnBorrow = program.dmTestOnBorrow !== undefined ? program.dmTestOnBorrow : false;
  program.dmValidationQuery = program.dmValidationQuery || "select 1;";

  // MySQL连接参数默认值
  program.mysqlDatabase = program.mysqlDatabase || "";
  program.mysqlCharset = program.mysqlCharset || "UTF8_GENERAL_CI";
  program.mysqlTimezone = program.mysqlTimezone || "local";
  program.mysqlConnectTimeout = program.mysqlConnectTimeout ? parseInt(program.mysqlConnectTimeout) : 10000;
  program.mysqlStringifyObjects = program.mysqlStringifyObjects !== undefined ? program.mysqlStringifyObjects : false;
  program.mysqlSupportBigNumbers = program.mysqlSupportBigNumbers !== undefined ? program.mysqlSupportBigNumbers : false;
  program.mysqlBigNumberStrings = program.mysqlBigNumberStrings !== undefined ? program.mysqlBigNumberStrings : false;
  program.mysqlDateStrings = program.mysqlDateStrings !== undefined ? program.mysqlDateStrings : false;
  program.mysqlMultipleStatements = program.mysqlMultipleStatements !== undefined ? program.mysqlMultipleStatements : false;
  program.mysqlTrace = program.mysqlTrace !== undefined ? program.mysqlTrace : true;
  program.mysqlEnableKeepAlive = program.mysqlEnableKeepAlive !== undefined ? program.mysqlEnableKeepAlive : true;
  program.mysqlKeepAliveInitialDelay = program.mysqlKeepAliveInitialDelay ? parseInt(program.mysqlKeepAliveInitialDelay) : 0;

  // MySQL连接池参数默认值
  program.mysqlWaitForConnections = program.mysqlWaitForConnections !== undefined ? program.mysqlWaitForConnections : true;
  program.mysqlConnectionLimit = program.mysqlConnectionLimit ? parseInt(program.mysqlConnectionLimit) : 10;
  program.mysqlMaxIdle = program.mysqlMaxIdle ? parseInt(program.mysqlMaxIdle) : program.mysqlConnectionLimit;
  program.mysqlIdleTimeout = program.mysqlIdleTimeout ? parseInt(program.mysqlIdleTimeout) : 60000;
  program.mysqlQueueLimit = program.mysqlQueueLimit ? parseInt(program.mysqlQueueLimit) : 0;

  if (program.useCpuCores === "0") {
    program.useCpuCores = maxCpus;
  }

  if (program.ignoreTables) {
    let ignoreTables = program.ignoreTables.split(",");
    program.ignoreTables = {};
    for (var i = 0; i < ignoreTables.length; ++i) {
      program.ignoreTables[ignoreTables[i]] = ignoreTables[i];
    }
  } else {
    program.ignoreTables = {};
  }

  program.connectionLimit = 10;

  if (
    program.host === "localhost" ||
    program.host === "127.0.0.1" ||
    program.host === "::1"
  ) {
    program.dynamic = 1;
  }
  // console.log(program);
  /**************** END : default values ****************/
};
